package com.ruoyi.system.ali;

import cn.hutool.core.net.URLEncodeUtil;
import cn.hutool.core.util.HexUtil;
import cn.hutool.core.util.StrUtil;
import com.ruoyi.common.constant.ZfbAppIdConstants;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.enums.ChannelEnum;
import com.ruoyi.common.utils.BigDecimalUtil;
import com.ruoyi.common.utils.UrlHexUtil;
import com.ruoyi.common.utils.sign.SignMD5Util;
import com.ruoyi.system.biz.CashBizService;
import com.ruoyi.system.domain.Bank;
import com.ruoyi.system.domain.CashHistory;
import com.ruoyi.system.domain.Order;
import com.ruoyi.system.domain.UserRate;
import com.ruoyi.system.dto.ApiByPhoneAddDto;
import com.ruoyi.system.service.*;
import com.ruoyi.system.vo.ApiPayResultVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.nio.charset.Charset;
import java.util.TreeMap;

/**
 * 支付宝转账
 */
@Component
@Slf4j
public class ZfbPayService implements ChannelService {
    @Resource
    ISysConfigService configService;
    private static final String serverUrl = "https://openapi.alipay.com/gateway.do";
    @Resource
    private ZfbConfigService zfbConfigService;
    @Resource
    private BankService bankService;

    @Override
    public String getType() {
        return ChannelEnum.ZFB.getCode();
    }

    @Resource
    private CashBizService cashService;

    @Resource
    private ISysUserService userService;
    @Resource
    private RedisCache redisCache;
    @Resource
    private UserRateService userRateService;

    @Override
    public Object create(AliPayDto aliPayDto, Order order) {
        Bank bank = bankService.getRand(order.getAmount(), getType());
        return create(order, bank);
    }

    @Override
    public Object createByPhone(ApiByPhoneAddDto apiByPhoneAddDto, Order order) {
        Bank bank = bankService.getUserBank(order.getUserId(), order.getAmount(), getType());
        return create(order, bank);
    }

    public static void main(String[] args) throws UnsupportedEncodingException {
        String url = "https://ds.alipay.com/?from=m&appId=";
        String s = URLEncodeUtil.encodeAll(url, Charset.forName("UTF-16"));

        String s1 = HexUtil.encodeHexStr(url);
        System.out.println(s1);

        System.out.println(s);

    }

    //uid
    public Object create(Order order, Bank bank) {
        BigDecimal amount = order.getAmount();
//        Long userId = bank.getUserId();
//        BigDecimal limitAmout = redisCache.getCacheObject(limitAmoutKey + userId);
//        if (limitAmout == null || limitAmout.compareTo(max) >= 0) {//如果没金额 或者已经减少了1毛  初始化
//            limitAmout = new BigDecimal(0.01);
//        }
//        //金额减少一分
//        amount = amount.subtract(limitAmout);
//        redisCache.setCacheObject(limitAmoutKey + userId, limitAmout.add(new BigDecimal(0.01)), 10, TimeUnit.MINUTES);
        order.setAmount(BigDecimalUtil.setDecimal(amount));

        //冻结收款用户的金额
        CashHistory userCashHis = new CashHistory(bank.getUserId(), order.getAmount(), "reduce", "代收订单", "freeze");
        userCashHis.setOrderNo(order.getOrderNo());
        cashService.updateCash(bank.getUserId(), userCashHis);
        order.setChannelCode(this.getType());
        order.setChannelName(ChannelEnum.getName(this.getType()));
        order.setAccount(bank.getCardNo());
        order.setName(bank.getName());
        order.setType("hand");
        order.setBankName("支付宝");
        order.setUserId(bank.getUserId());
//        SysUser sysUser = userService.check(bank.getUserId());
        UserRate userRate = userRateService.checkUserRate(bank.getUserId(), this.getType());
        order.setEarning(order.getAmount().multiply(userRate.getRate().divide(new BigDecimal(100))));
        order.setUsername(bank.getUsername());
        order.setZfbUserId(bank.getZfbUserId());
        ApiPayResultVo apiVo = new ApiPayResultVo();
        apiVo.setAmount(String.valueOf(order.getAmount()));
        apiVo.setOrderNo(order.getOrderNo());
        apiVo.setMerchantId(order.getMerchantId());
        TreeMap<String, String> map = SignMD5Util.objToMap(apiVo);
        map.put("payType", "6");
        String sign = SignMD5Util.getSign(map, "sign");
        String payUrl = configService.selectConfigByKey("template");
        payUrl = payUrl + "?" + SignMD5Util.getStr(map, sign);
        apiVo.setUrl(payUrl);
        //order.setZfbUrl("https://ds.alipay.com/?from=m&appId=20000116&actionType=toAccount&goBack=NO");
        /*
//https://render.alipay.com/p/s/i?scheme=alipays://platformapi/startapp?saId=10000007&qrcode=https://qr.alipay.com/fkx16910kjc76ds0g0pocc1?_s=web-other
        if (StrUtil.isNotBlank(bank.getZfbUrl())) {

            String schemeUrl = "alipays://platformapi/startapp?saId=10000007&qrcode=" + bank.getZfbUrl();


            //编码
            schemeUrl = UrlHexUtil.encode(schemeUrl);
            String url = ZfbAppIdConstants.toZfbScheme + schemeUrl;
            try {
                //将链接解析成二维码
//                BigDecimal bigDecimal = BigDecimalUtil.getNumber(apiVo.getAmount());
//
//                QrConfig qrConfig = new QrConfig();
//                qrConfig.setWidth(200);
//                qrConfig.setHeight(200);
//                byte[] bytes = QrCodeUtil.generatePng(url, qrConfig);
//                String projectName = configService.selectConfigByKey("projectName");
//                String picUrl = AliOss.uploadToOss(bytes, projectName + "/orderReceive/" + apiVo.getOrderNo() + ".jpg");
                order.setZfbUrl(url);

            } catch (Exception e) {
                log.info("支付宝转账转二维码失败:{}", e.getMessage());
            }
        }
*/

        return apiVo;
    }


}
